using System.Collections.Generic;
using LitJson;
using UnityEngine;
using UnityEngine.UI;
namespace CGF
{
    public partial class PanelWithdrawEdit : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private JsonData wayData;
        private List<string> bankCodes =  new List<string>();
        private string currPixType;
        private string pixInputContent = "";

        public static void Open(Sprite iconSprite, JsonData wayData)
        {
            var instance = UIManagerComponent.instance.OpenUI<PanelWithdrawEdit>(UILayer.Normal, RootComponent.instance, true);
            instance.SetProsBindCompletedAction(() =>
            {
                instance.SetInfo(iconSprite, wayData);
            });
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelWithdrawEdit>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelWithdrawEdit", layer, isFloat);
            BindProperties(transform);

            BtnClose.SetClick(Close);
            
            VNBankDropdown.rectTransform.anchoredPosition = new Vector2(0, VNBankDropdown.rectTransform.anchoredPosition.y);
            
            BtnPixSelect.SetClick(() =>
            {
                PixDropdown.Show();
            });
            PixDropdown.SetOnSelect(index =>
            {
                BtnPixSelect.text.text = PixDropdown.cells[index].text.text;
                if (currPixType != BtnPixSelect.text.text)
                {
                    currPixType = BtnPixSelect.text.text;
                    InputPIXAccount.text = "";
                }
                if (currPixType == "CPF")
                {
                    InputPIXAccount.characterLimit = 14;
                }
                else if (currPixType == "Email")
                {
                    InputPIXAccount.characterLimit = 35;
                }
                else if (currPixType == "Phone")
                {
                    InputPIXAccount.characterLimit = 11;
                }
            });

            InputPIXAccount.SetInputAction(input =>
            {
                if (currPixType == "CPF" && pixInputContent.Length < input.Length)
                {
                    if (InputPIXAccount.text.Length == 3 || InputPIXAccount.text.Length == 7)
                    {
                        InputPIXAccount.text += ".";
                        InputPIXAccount.MoveTextEnd(false);
                    }
                    else if (InputPIXAccount.text.Length == 11)
                    {
                        InputPIXAccount.text += "-";
                        InputPIXAccount.MoveTextEnd(false);
                    }
                }
                pixInputContent = input;
            }, false);

            BtnConfirm.SetClick(async () =>
            {
                string method = wayData["method"].ToString();
                switch (method)
                {
                    case "pix":
                        if (BtnPixSelect.text.text == "CPF")
                        {
                            if (!StringHelper.IsPIX(InputPIXAccount.text))
                            {
                                CGF.Dialog.Alert(CommAssets.instance.I18N_invalid_cformat);
                                return;
                            }
                        }
                        else if (BtnPixSelect.text.text == "Email")
                        {
                            if (!StringHelper.IsEmail(InputPIXAccount.text))
                            {
                                CGF.Dialog.Alert(CommAssets.instance.I18N_invalid_cformat);
                                return;
                            }
                        }
                        else if (BtnPixSelect.text.text == "Phone")
                        {
                            InputPIXAccount.text = InputPIXAccount.text.Replace("+55", "");
                            if (InputPIXAccount.text.StartsWith("55"))
                            {
                                InputPIXAccount.text = InputPIXAccount.text.Substring(2);
                            }
                            if (!StringHelper.IsPhoneNum(InputPIXAccount.text))
                            {
                                CGF.Dialog.Alert(CommAssets.instance.I18N_invalid_cformat);
                                return;
                            }
                        }
                        wayData["account"] = InputPIXAccount.text;
                        wayData["bank_code"] = currPixType;
                        break;
                    case "usdt":
                        if (string.IsNullOrEmpty(InputAccount.text))
                        {
                            CGF.Dialog.Alert(I18N_please_input_account);
                            return;
                        }
                        if (InputAccount.text.Contains(" "))
                        {
                            CGF.Dialog.Alert(CommAssets.instance.I18N_account_canot_space);
                            return;
                        }
                        wayData["account"] = InputAccount.text;
                        break;
                    case "bank":
                        if (string.IsNullOrEmpty(InputAccount.text))
                        {
                            CGF.Dialog.Alert(I18N_please_input_account);
                            return;
                        }
                        if (InputAccount.text.Contains(" "))
                        {
                            CGF.Dialog.Alert(CommAssets.instance.I18N_account_canot_space);
                            return;
                        }
                        wayData["account"] = InputAccount.text;
                        wayData["bank_owner"] = InputName.text;
                        wayData["bank_code"] = Config.BankCodes[CGFConfig.Instance.ReleaseArea][BtnBankCode.gameObject.Get<Text>("Name").text];
                        break;
                }
                JsonData data = new JsonData();
                data["method"] = wayData["method"];
                data["account"] = wayData["account"];
                data["bank_owner"] = wayData["bank_owner"];
                data["bank_code"] = wayData["bank_code"];
                data["user_id"] = UserInfo.Info["id"];
                string id = wayData["id"].ToString();
                var res = await Network.Put($"/v1/withdrawal/way/{id}", data);
                if (res.success)
                {
                    RootComponent.instance.GetComponent<PanelWithdraw>().RefreshMethodData(wayData);
                    CGF.Dialog.Alert(I18N_add_success, Close);
                }
            });
            
            VNBankDropdown.SetCellUpdateCallback((RectTransform cell, int index) =>
            {
                cell.gameObject.Get<Text>("Text").text = bankCodes[index];
                cell.GetComponent<CButton>().SetClick(() =>
                {
                    BtnBankCode.gameObject.Get<Text>("Name").text = bankCodes[index];
                    VNBankDropdown.GetComponent<Dropdown>().Hide();
                });
            });
            bankCodes = new List<string>(Config.BankCodes[CGFConfig.Instance.ReleaseArea].Keys);
            bankCodes.Sort();
            VNBankDropdown.SetTotalNumber(bankCodes.Count);
            BtnBankCode.SetClick(() =>
            {
                VNBankDropdown.GetComponent<Dropdown>().Show();
            });
            
            ScaleIn(Dialog.transform);
        }

        private void SetInfo(Sprite iconSprite, JsonData wayData)
        {
            Debug.Log($"编辑：{wayData.ToJson()}");
            this.wayData = wayData;
            WayIcon.sprite = iconSprite;
            WayIcon.SetNativeSize();
            string method = this.wayData["method"].ToString();
            WayName.text = method.ToUpper();
            switch (WayName.text)
            {
                case "PIX":
                    BtnBankCode.gameObject.SetActive(false);
                    InputName.gameObject.SetActive(false);
                    InputAccount.gameObject.SetActive(false);
                    InputPIX.gameObject.SetActive(true);
                    currPixType = this.wayData["bank_code"].ToString();
                    if (string.IsNullOrEmpty(currPixType))
                    {
                        currPixType = "CPF";
                    }
                    BtnPixSelect.text.text = currPixType;
                    if (currPixType == "CPF")
                    {
                        InputPIXAccount.characterLimit = 14;
                    }
                    else if (currPixType == "Email")
                    {
                        InputPIXAccount.characterLimit = 35;
                    }
                    else if (currPixType == "Phone")
                    {
                        InputPIXAccount.characterLimit = 11;
                    }
                    InputPIXAccount.text = wayData["account"].ToString();
                    break;
                case "USDT":
                    WayName.text += "<size=20>(TRC20)</size>";
                    BtnBankCode.gameObject.SetActive(false);
                    InputName.gameObject.SetActive(false);
                    InputPIX.gameObject.SetActive(false);
                    InputAccount.gameObject.SetActive(true);
                    InputAccount.text = wayData["account"].ToString();
                    break;
                case "BANK":
                    InputPIX.gameObject.SetActive(false);
                    BtnBankCode.gameObject.SetActive(true);
                    InputName.gameObject.SetActive(true);
                    InputAccount.gameObject.SetActive(true);
                    string bankCode = wayData["bank_code"].ToString();
                    string bankName = "";
                    Dictionary<string, string> banks = Config.BankCodes[CGFConfig.Instance.ReleaseArea];
                    foreach (var bank in banks)
                    {
                        if (bank.Value == bankCode)
                        {
                            bankName = bank.Key;
                            break;
                        }
                    }
                    BtnBankCode.gameObject.Get<Text>("Name").text = bankName;
                    InputName.text = wayData["bank_owner"].ToString();
                    InputAccount.text = wayData["account"].ToString();
                    break;
            }
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
